package org.txazo.blog.dao.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.stereotype.Repository;
import org.txazo.blog.dao.MemberInfoDao;
import org.txazo.blog.vo.MemberInfo;

/**
 * 用户信息数据访问实现
 * 
 * @author Tu XiaoZhou
 * @since 2013-08-10
 */
@Repository("memberInfoDao")
public class MemberInfoDaoImpl implements MemberInfoDao {

	@Autowired
	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	@Override
	public boolean isEmailAccountExist(String emailAccount) {
		String sql = "select count(0) from blog.MemberInfo where emailAccount = ?";
		return namedParameterJdbcTemplate.getJdbcOperations().queryForObject(
				sql, Integer.class, emailAccount) == 1;
	}

	@Override
	public boolean addMemberInfo(MemberInfo memberInfo) {
		String sql = "insert into blog.MemberInfo (emailAccount, nickname, sex, regTime, lastLoginTime, lastModTime) values (?, ?, ?, ?, ?, ?)";
		return namedParameterJdbcTemplate.getJdbcOperations().update(
				sql,
				new Object[] { memberInfo.getEmailAccount(),
						memberInfo.getNickname(), memberInfo.getSex(),
						memberInfo.getRegTime(), memberInfo.getLastLoginTime(),
						memberInfo.getLastModTime() }) == 1;

	}

	@Override
	public boolean updateMemberInfo(MemberInfo memberInfo) {
		String sql = "update blog.MemberInfo set (nickname, sex, lastLoginTime, lastModTime) =  (?, ?, ?, ?) where memberId = ?";
		return namedParameterJdbcTemplate.getJdbcOperations()
				.update(sql,
						new Object[] { memberInfo.getNickname(),
								memberInfo.getSex(), memberInfo.getRegTime(),
								memberInfo.getLastLoginTime(),
								memberInfo.getLastModTime(),
								memberInfo.getMemberId() }) == 1;
	}

	@Override
	public MemberInfo getMemberInfo(String emailAccount) {
		MemberInfo memberInfo = null;
		String sql = "select * from blog.MemberInfo where emailAccount = ?";
		try {
			memberInfo = namedParameterJdbcTemplate.getJdbcOperations()
					.queryForObject(
							sql,
							ParameterizedBeanPropertyRowMapper
									.newInstance(MemberInfo.class),
							new Object[] { emailAccount });
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
		return memberInfo;
	}

	@Override
	public int getMemberId(String emailAccount) {
		String sql = "select memberId from blog.MemberInfo where emailAccount = ?";
		return namedParameterJdbcTemplate.getJdbcOperations().queryForObject(
				sql, Integer.class, emailAccount);
	}

}
